<?php

if( !defined( 'MEDIAWIKI' ) )
die(-1);

require_once('DatabaseFunctions.php');



#install extension hook
$wgHooks['BeforePageDisplay'][] = "wfGenres";


function wfGenres(){
  global $wgTitle, $wgDBprefix, $wgOut, $wgCategory, $wgMemc,$wgCorrespondence;
  $start_time = microtime(true);
  $dbr = wfGetDB( DB_SLAVE );
  
   $correspondence=$wgCorrespondence;
  
  $sql = "select genre, s.Count w from ss_tags t inner join searches s on t.idtags=s.idtags where s.query='groupby=attr:genreKey;select=idtags as idtags,sum(TotalCount*weightTags) as Count;groupsort=Count desc;!filter=genreKey,0;limit=15;filter=type,1' order by genre;"; 
  $res = $dbr->query($sql);
  //insert tags in array from database
  while ($row = $dbr->fetchObject( $res )) {
   $total_weight += $row->w;
   $id=crcGenre($row->genre);
   $genres[$id][0]=$row->w;
   $genres[$id][1]=$row->genre;
  }
  $dbr->freeResult($res);
  
  foreach ($correspondence as $key => $value){
	if (isset($genres[$key]) && isset($genres[$value])){
		$genres[$value][0]+=$genres[$key][0];
	}
  }
  
  //foreach ($tags as $key => $value)
  foreach ($genres as $key => $value)
  {
    //$values = explode("@", $value);
	$values[0]=$value[1];
	$values[1]=$value[0];
    $x = $values[1]/$total_weight;
    //if ($x>0.01) $bold=" style='font-weight:bold'"; else $bold="";
    //$query_search = str_replace(' ', ' <wbr />',$values[0]);
    //$values[0] = str_replace('/','',$values[0]);
	if (!isset($correspondence[$key]))
		$genresHtml .= "<li><a $bold title='{$values[0]}' href='/genres/".wfUrlencode($values[0])."'>{$values[0]}</a></li>";
  }

  $more = mb_convert_case(wfMsg("more"), MB_CASE_LOWER);
  $genresHtml .= "<li><a title='$more...' href='/genres/'>$more...</a></li>";
  $wgOut->setGenres($genresHtml);

  return true;
}
